package com.zzsz.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.zzsz.common.core.controller.BaseController;
import com.zzsz.common.core.domain.AjaxResult;
import com.zzsz.domain.EmailLog;
import com.zzsz.service.EmailLogService;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * --- 这有何难 ---
 * ƪ(˘⌣˘)ʃ
 *
 * @author 超级无敌张恒阳大王
 * @date 5/9/2025
 * @desc 邮件日志控制器
 */
@Slf4j
@RestController
@RequestMapping("/warn/emailLog")
public class EmailLogController extends BaseController {

	@Autowired
	private EmailLogService emailLogService;
	// 推送稳定版本

	/**
	 * 获取邮件日志列表
	 */
	@GetMapping("/list")
	public AjaxResult getEmailLogList(@RequestParam(defaultValue = "1") Integer pageNum,
									  @RequestParam(defaultValue = "10") Integer pageSize,
									  String fromEmail,
									  String toEmail,
									  String subject,
									  Boolean sendSuccess) {
		Map<String, Object> params = new HashMap<>();
		params.put("pageNum", pageNum);
		params.put("pageSize", pageSize);
		params.put("fromEmail", fromEmail);
		params.put("toEmail", toEmail);
		params.put("subject", subject);
		params.put("sendSuccess", sendSuccess);

		PageInfo<EmailLog> emailLogPageInfo = emailLogService.getEmailLogList(params);
		log.debug("emailLogPageInfo: {}", emailLogPageInfo);
		return AjaxResult.success(emailLogPageInfo);
	}

	/**
	 * 获取邮件日志详情
	 *
	 * @param id 日志ID
	 * @return 邮件日志详情
	 */
	@GetMapping("/{id}")
	public AjaxResult getEmailLogDetail(@PathVariable Long id) {
		EmailLog emailLog = emailLogService.getEmailLogDetail(id);
		if (emailLog == null) {
			return AjaxResult.error("邮件日志不存在");
		}
		return AjaxResult.success(emailLog);
	}

	/**
	 * 批量删除邮件日志
	 *
	 * @param ids 日志ID列表
	 * @return 操作结果
	 */
	@DeleteMapping("/batch")
	public AjaxResult deleteEmailLogs(@RequestBody Long[] ids) {
		if (ids == null || ids.length == 0) {
			return AjaxResult.error("请选择要删除的邮件日志");
		}
		int result = emailLogService.deleteEmailLogs(ids);
		if (result > 0) {
			return AjaxResult.success("删除成功");
		} else {
			return AjaxResult.error("删除失败");
		}
	}

	/**
	 * 导出邮件日志列表为Excel
	 *
	 * @param response HTTP响应
	 */
	@GetMapping("/export")
	public void exportEmailLogList(HttpServletResponse response,
								   String fromEmail,
								   String toEmail,
								   String subject,
								   Boolean sendSuccess) {
		try {
			// 1. 构建查询参数
			Map<String, Object> params = new HashMap<>();
			params.put("fromEmail", fromEmail);
			params.put("toEmail", toEmail);
			params.put("subject", subject);
			params.put("sendSuccess", sendSuccess);

			// 2. 获取所有符合条件的邮件日志数据
			List<EmailLog> emailLogList = emailLogService.exportEmailLogs(params);
			log.info("导出邮件日志列表，共{}条数据", emailLogList.size());

			// 3. 设置响应头，告诉浏览器这是一个下载文件
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("UTF-8");
			// 生成文件名，包含当前日期
			String fileName = "邮件日志列表_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xlsx";
			// URL编码，防止中文乱码
			String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%");
			response.setHeader("Content-disposition", "attachment;filename=" + encodedFileName);

			// 4. 创建EasyExcel的写入样式策略
			// 头的策略
			WriteCellStyle headWriteCellStyle = new WriteCellStyle();
			// 设置头背景色
			headWriteCellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
			// 设置头字体
			WriteFont headWriteFont = new WriteFont();
			headWriteFont.setFontHeightInPoints((short) 20);
			headWriteFont.setBold(true);
			headWriteCellStyle.setWriteFont(headWriteFont);
			// 内容的策略
			WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
			// 设置内容背景色
			contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
			// 设置内容字体
			WriteFont contentWriteFont = new WriteFont();
			contentWriteFont.setFontHeightInPoints((short) 14);
			contentWriteCellStyle.setWriteFont(contentWriteFont);
			// 应用策略
			HorizontalCellStyleStrategy styleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

			// 5. 使用EasyExcel写入数据到响应流
			EasyExcel.write(response.getOutputStream(), EmailLog.class)
					.registerWriteHandler(styleStrategy)
					.sheet("邮件日志列表")
					.doWrite(emailLogList);
		} catch (Exception e) {
			log.error("导出邮件日志列表失败", e);
			// 如果导出失败，设置响应状态为500
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			try {
				response.getWriter().write("导出失败：" + e.getMessage());
			} catch (IOException ex) {
				log.error("写入错误信息失败", ex);
				// 111
			}
		}
	}
}